package com.smsc.headend.connector.netty.handler;

import com.smsc.headend.connector.netty.NettyConfigHelper;
import com.smsc.headend.connector.service.DeviceConnectService;
import com.smsc.headend.connector.service.TerminalChannelService;
import com.smsc.headend.connector.utils.NetUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * client handler
 */
@Slf4j
@ChannelHandler.Sharable
public class SMSCNettyHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    DeviceConnectService deviceConnectService;
    @Autowired
    TerminalChannelService terminalChannelService;
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        try {
            byte[] result = new byte[buf.readableBytes()];
            buf.readBytes(result);
            Future<byte[]> ob = ctx.executor().submit(() -> deviceConnectService.clientAccept(ctx.channel(), result));
            if (ob.get(30, TimeUnit.SECONDS) != null) {
                ctx.writeAndFlush(ob);
            }
        }
        finally {
            buf.release();
        }
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("connected");
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("channel disconnect");
        NettyConfigHelper.removeChannel(ctx.channel());
        deviceConnectService.deviceDisconnect(ctx.channel());
        super.channelInactive(ctx);
    }
}
